const Promise = require('bluebird');
const redis = require('../../../service/external/redis')('mingmou_log');
const mysql = require('../../../service/external/mysql');
const upStats = mysql['upStats'];
const moment = require('moment');
const services = require('../../../service');
const kalifa = require('../../../service/external/kalifa');
const {ResponseError} = require('ruo');
const Sequelize = require('sequelize');

const tables = 'domain_total_request_size-2022-04';
const date = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');

module.exports = {
  async get(req, res) {
    const {account_id} = req.user;
    const {start_time, end_time, domain} = req.query;
    const startTime = moment(start_time);
    const endTime = moment(end_time);

    if (!startTime.isValid() || !endTime.isValid()) {
      throw new ResponseError('InvalidDateTime');
    }
    if (startTime > endTime) {
      throw new ResponseError('SearchStartDateGteEndDate');
    }
    if (startTime < moment().subtract(183, 'days')) {
      throw new ResponseError('SearchDateIsOutOf180Days');
    }
    if (startTime.clone().add('31', 'days') < endTime) {
      throw new ResponseError('CantTBeyond30Days');
    }

    const bucket = await services.Bucket.getByUrlAsync(domain, {account_id, recursion: false});

    const statParams = {
      bucket_id: bucket.bucket_id,
      bucket_domain: domain,
      start_time: startTime.format('YYYY-MM-DD HH:mm:ss'),
      end_time: endTime.format('YYYY-MM-DD HH:mm:ss'),
    };

    const {data: stats} = await kalifa.callAsync('v2.stat.get', statParams);

    const result = await Promise.map(stats, async ({time}) => {
      const bf_cp_bytes = await redis.get(`${domain}:totalRsize:${time - 300}`);
      const data = Number(bf_cp_bytes) || 0;
      const total_size = `${domain}:totalRsize:${time - 300}`;
      const value = data;
      await insertData(bucket.bucket_id, domain, total_size, value);
    }, {concurrency: 3});
    res.send({result});
  },

};

async function insertData(bucket_id, domain, total_size, value) {

  const sql = `insert into '${tables}' (bucket_id, domain, pubtime, total_size, value) VALUES ('${bucket_id}', '${domain}', '${date}', '${total_size}', '${value}')`;
  await upStats.query(sql, {
    type: Sequelize.QueryTypes.INSERT,
  });
}



